package grimbo.goodwinfooty.server.mvc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 * @author paul
 * 
 */
public class ClearDataController extends AbstractController {
	private static final String CNAME = ClearDataController.class.getName();
	private static final Logger log = Logger.getLogger(CNAME);

	private PersistenceManagerFactory persistenceManagerFactory;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		final String MNAME = "handleRequestInternal(HttpServletRequest, HttpServletResponse)";
		final boolean DEBUG = log.isLoggable(Level.FINE);
		log.entering(CNAME, MNAME);

		res.setContentType("text/plain");

		String[] queries = createQueries(req);

		Map result = null;

		if ((null != queries) && (queries.length > 0)) {
			result = clearUsingJDO(queries);
		}

		res.getWriter().print(result);

		log.exiting(CNAME, MNAME);

		return null;
	}

	private String[] createQueries(HttpServletRequest req) {
		String[] queries = req.getParameterValues("q");
		return queries;
	}

	private Map clearUsingJDO(String[] queries) {
		Map result = new HashMap();
		PersistenceManager pm = null;
		try {
			pm = persistenceManagerFactory.getPersistenceManager();
			for (int i = 0; i < queries.length; i++) {
				String q = queries[i];
				if ((null == q) || ("".equals(q.trim()))) {
					throw new IllegalArgumentException(
							"Query string cannot be null or empty.");
				}
				Query query = pm.newQuery(q);
				List list = (List) query.execute();
				int count = (null != list) ? list.size() : 0;
				log.info("found " + count + " items for query " + q + ".");
				result.put(String.valueOf(query), new Integer(count));
				pm.deletePersistentAll(list);
			}
		} finally {
			pm.close();
		}
		return result;
	}

	public PersistenceManagerFactory getPersistenceManagerFactory() {
		return persistenceManagerFactory;
	}

	public void setPersistenceManagerFactory(
			PersistenceManagerFactory persistenceManagerFactory) {
		this.persistenceManagerFactory = persistenceManagerFactory;
	}
}
